<template>
	<view class="scene-detail-wrap">
		<view class="name-wrap">
			<u--input clearable border="false" placeholder="请输入名称"
				:customStyle="{ backgroundColor: '#fff',  padding: '12px 30rpx', borderRadius: '10rpx' }" fontSize="16"
				v-model="sceneData.sceneName"></u--input>
		</view>
		<view class="container-wrap">
			<view class="cell-group-wrap">
				<u-cell-group :border="false">
					<view class="cell-wrap">
						<u-cell size="large" :border="false" title="场景状态">
							<u-switch v-model="sceneData.enable" slot="value" :activeValue="1" :inactiveValue="2"
								activeColor="#3C9CFF" inactiveColor="#dbdbdb" size="18"></u-switch>
						</u-cell>
					</view>
				</u-cell-group>
			</view>
			<view class="condition-wrap">
				<view class="title-wrap">
					<view class="left-wrap">
						<text class="title">触发器</text>
						<u--text suffixIcon="arrow-down" iconStyle="font-size: 10px; margin-left: 10rpx"
							:text="getCondName(sceneData.cond)" color="#868686" size="12" margin="10rpx 0 0"
							@click="isCond = true"></u--text>
					</view>
					<view class="right-wrap">
						<u-icon name="plus-circle-fill" size="24" color='#3c9cff' bold
							@click="handleAddTrigger"></u-icon>
					</view>
				</view>
				<view v-if="sceneData.triggers.length === 0" class="empty-cell" @click="handleAddTrigger">
					<view class="text">添加条件</view>
				</view>
				<view v-else class="swipe-action-wrap">
					<u-swipe-action autoClose>
						<u-cell-group :border="false">
							<!-- 设置key为不同id是为了解决uview的SwipeAction 滑动单元格 关闭事件 ，删除当前项，下一项自动弹出删除选择bug -->
							<view class="action-item-wrap" v-for="(item,index) in sceneData.triggers"
								:key="getKey(index, item)">
								<u-swipe-action-item :options="swipeOptions"
									@click="handleDeleteSceneItem('trigger', index)">
									<u-cell :border="false" isLink
										@click="handleEditSceneItem({type:'trigger', item:item, index:index})">
										<view slot="title" class="slot-title">
											<u--image :src="getImageUrl(item)" radius="4" width="33"
												height="33"></u--image>
											<view class="cell-text">
												<view class="title">
													{{item.productName}}{{item.cronExpression ? 'CRON' : ''}}
												</view>
												<view v-if="item.deviceCount > 0" class="des">设备数量：{{item.deviceCount}}
													个
												</view>
												<view class="des">
													<template v-if="item.parentName && item.parentName !== item.name">
														{{item.parentName}} >>
													</template>
													<template v-if="item.arrayIndexName">
														{{item.arrayIndexName}} >>
													</template>
													{{item.name}}
													{{item.value !== '' ?  item.operator ? `${item.operator} ${item.value}` : item.value : ''}}
													<!-- 定时触发事件 -->
													{{item.cronExpression ? item.cronExpression : ''}}
													<!-- 触发条件为上下线设备 -->
													{{item.type === 5 ? '设备上线' : item.type === 6 ? '设备下线' : ''}}
												</view>
											</view>
										</view>
									</u-cell>
								</u-swipe-action-item>
							</view>
						</u-cell-group>
					</u-swipe-action>
				</view>
			</view>
			<view class="execute-wrap">
				<view class="title-wrap">
					<view class="left-wrap">
						<text class="title">执行动作</text>
					</view>
					<view class="right-wrap">
						<u-icon name="plus-circle-fill" size="24" color='#3c9cff' bold
							@click="handleAddAction"></u-icon>
					</view>
				</view>
				<view v-if="sceneData.actions.length === 0" class="empty-cell" @click="handleAddAction">
					<view class="text">添加任务</view>
				</view>
				<view v-else class="swipe-action-wrap">
					<u-swipe-action autoClose>
						<u-cell-group :border="false">
							<view class="action-item-wrap" v-for="(item,index) in sceneData.actions"
								:key="getKey(index, item)">
								<!-- 设置key为不同id是为了解决uview的SwipeAction 滑动单元格 关闭事件 ，删除当前项，下一项自动弹出删除选择bug -->
								<u-swipe-action-item :options="swipeOptions"
									@click="handleDeleteSceneItem('action', index)">
									<u-cell :border="false" isLink
										@click="handleEditSceneItem({type:'action', item:item, index:index})">
										<view slot="title" class="slot-title">
											<u--image :src="getImageUrl(item)" radius="4" width="33"
												height="33"></u--image>
											<view class="cell-text">
												<!-- 告警执行 -->
												<view class="title">{{item.productName}}{{item.source ? '告警执行' : ''}}
												</view>
												<view v-if="item.deviceCount > 0" class="des">设备数量：{{item.deviceCount}}
													个
												</view>
												<view class="des">
													<template v-if="item.parentName && item.parentName !== item.name">
														{{item.parentName}} >>
													</template>
													<template v-if="item.arrayIndexName">
														{{item.arrayIndexName}} >>
													</template>
													{{item.name}}
													{{item.value !== '' ? item.value : ''}}
												</view>
											</view>
										</view>
									</u-cell>
								</u-swipe-action-item>
							</view>
						</u-cell-group>
					</u-swipe-action>
				</view>
			</view>

			<view class="cell-group-wrap">
				<u-cell-group :border="false">
					<view class="cell-wrap">
						<u-cell size="large" :border="false" title="更多设置" isLink @click="handleMore"></u-cell>
					</view>
				</u-cell-group>
			</view>

			<view class="btn-save-wrap">
				<u-button type="primary" :customStyle="{ height: '96rpx' }" size="normal" text="保存"
					@click="handleSave"></u-button>
			</view>
		</view>
		<view class="other">
			<u-popup :show="isCond" :round="5" mode="bottom" :closeOnClickOverlay="true" @close="isCond = false">
				<view class="cond-popup-wrap">
					<view class="cell-group-wrap">
						<u-cell-group :border="false">
							<view class="cell-wrap">
								<u-cell title="任意条件" :name="1" @click="handleConfirmCond"></u-cell>
							</view>
							<view class="cell-wrap">
								<u-cell title="所有条件" :name="2" @click="handleConfirmCond"></u-cell>
							</view>
							<view class="cell-wrap">
								<u-cell title="不满足" :name="3" @click="handleConfirmCond"></u-cell>
							</view>
							<view class="cell-wrap">
								<u-cell title="取消" name="cancel" :border="false" @click="handleConfirmCond"></u-cell>
							</view>
						</u-cell-group>
					</view>
				</view>
			</u-popup>

			<u-popup :show="isMore" :round="5" mode="bottom" bgColor="#eef3f7" :closeOnClickOverlay="true"
				@close="isMore = false">
				<view class="more-popup-wrap">
					<view class="remark">静默时间：在设定的时间范围内将不再重复执行；延时执行：延时不会存储，限制为90秒内。</view>
					<view class="form-wrap">
						<u--form :model="more" labelPosition="left" labelWidth="80">
							<view class="form-item-wrap">
								<u-form-item label="静默时间" prop="more.silentPeriod">
									<u-input v-model="more.silentPeriod" border="none" type="number" inputAlign="right"
										placeholder="请输入静默时间" clearable>
										<u--text text="分钟" slot="suffix" margin="0 0 0 6rpx" type="tips"></u--text>
									</u-input>
								</u-form-item>
							</view>
							<view class="form-item-wrap">
								<u-form-item label="执行方式" prop="more.executeMode">
									<template slot="right">
										<u-radio-group v-model="more.executeMode">
											<u-radio label="串行" :name="1" :customStyle="{marginRight: '30rpx'}">
											</u-radio>
											<u-radio label="并行" :name="2">
											</u-radio>
										</u-radio-group>
									</template>
								</u-form-item>
							</view>
							<view class="form-item-wrap">
								<u-form-item label="延时执行" prop="more.executeDelay">
									<u-input v-model="more.executeDelay" border="none" type="number" inputAlign="right"
										placeholder="请输入延长时间" clearable>
										<u--text text="秒钟" slot="suffix" margin="0 0 0 6rpx" type="tips"></u--text>
									</u-input>
								</u-form-item>
							</view>
						</u--form>
					</view>
					<u-button type="primary" @click="handleConfirmMore">完成</u-button>
				</view>
			</u-popup>

			<u-popup :show="isTrigger" :round="5" mode="bottom" :closeOnClickOverlay="true" @close="isTrigger = false">
				<view class="trigger-popup-wrap">
					<view class="title">添加条件</view>
					<view class="cell-group-wrap">
						<u-cell-group :border="false">
							<view class="cell-wrap">
								<u-cell title="设备触发" icon="/static/scene/device.png"
									:iconStyle="{ marginRight: '10rpx' }" :border="false" isLink
									@click="goToDeviceList('trigger')"></u-cell>
							</view>
							<view class="cell-wrap" v-if="deptId!=null">
								<u-cell title="产品触发" icon="/static/scene/product.png"
									:iconStyle="{ marginRight: '10rpx' }" :border="false" isLink
									@click="goToProductList('trigger')"></u-cell>
							</view>
							<view class="cell-wrap">
								<u-cell title="定时触发" icon="/static/scene/timing.png"
									:iconStyle="{ marginRight: '10rpx' }" :border="false" isLink
									@click="goToTimingList('trigger')"></u-cell>
							</view>
						</u-cell-group>
					</view>
				</view>
			</u-popup>

			<u-popup :show="isAction" :round="5" mode="bottom" :closeOnClickOverlay="true" @close="isAction = false">
				<view class="trigger-popup-wrap">
					<view class="title">添加任务</view>
					<view class="cell-group-wrap">
						<u-cell-group :border="false">	
							<view class="cell-wrap">
								<u-cell title="设备执行" icon="/static/scene/device.png"
									:iconStyle="{ marginRight: '10rpx' }" :border="false" isLink
									@click="goToDeviceList('action')"></u-cell>
							</view>
							<view class="cell-wrap" v-if="deptId!=null">
								<u-cell title="产品执行" icon="/static/scene/product.png"
									:iconStyle="{ marginRight: '10rpx' }" :border="false" isLink
									@click="goToProductList('action')"></u-cell>
							</view>
							<view class="cell-wrap">
								<u-cell title="告警执行" icon="/static/scene/alarm.png"
									:iconStyle="{ marginRight: '10rpx' }" :border="false"
									@click="goToWarningList('action')" isLink></u-cell>
							</view>
						</u-cell-group>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import {
		getScene,
		addScene,
		updateScene
	} from '@/apis/modules/scene.js';

	export default {
		data () {
			return {
				sceneId: null,
				isCond: false,
				isMore: false,
				isTrigger: false,
				isAction: false,
				deptId: null,
				// 更多设置
				more: {
					silentPeriod: 0,
					executeMode: 1,
					executeDelay: 0
				},
				swipeOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				sceneData: {
					triggers: [],
					actions: []
				},

			};
		},
		onLoad (option) {
			this.deptId = this.profile.deptId;
			this.sceneId = Number(option.sceneId);
			if (this.sceneId) {
				this.getDetail();
			} else {
				this.sceneData = uni.getStorageSync('sceneData');
			}
		},
		onShow () {
			const callback = uni.getStorageSync('callback');
			if (callback) {
				this.sceneData = uni.getStorageSync('sceneData');
			}
		},
		onHide () {
			// 页面隐藏时关闭弹框
			this.isTrigger = false;
			this.isAction = false;
			// 保存当前页面数据
			uni.setStorageSync('sceneData', this.sceneData);
		},
		methods: {
			// 获取一键任务详情
			getDetail () {
				getScene(this.sceneId).then(res => {
					if (res.code === 200) {
						this.sceneData = {
							...res.data
						};
						uni.setStorageSync('sceneData', this.sceneData);
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						});
					}
				}).catch(err => {
					console.log('场景详情:', err);
				})
			},
			// 获取条件
			getCondName (cond) {
				if (cond === 1) {
					return '任意条件'
				} else if (cond === 2) {
					return '所有条件'
				} else if (cond === 3) {
					return '不满足'
				} else {
					return '未知'
				}
			},
			// 确认选择条件
			handleConfirmCond ({
				name
			}) {
				if (name !== 'cancel') {
					this.sceneData.cond = name;
				}
				this.isCond = false;
			},
			// 更多设置
			handleMore () {
				const sceneData = uni.getStorageSync('sceneData');
				const {
					silentPeriod,
					executeMode,
					executeDelay
				} = sceneData;
				this.more = {
					silentPeriod,
					executeMode,
					executeDelay
				};
				this.isMore = true;
			},
			// 确认选择更多
			handleConfirmMore () {
				const {
					silentPeriod,
					executeMode,
					executeDelay
				} = this.more;
				let sceneData = uni.getStorageSync('sceneData');
				sceneData = {
					...sceneData,
					silentPeriod,
					executeMode,
					executeDelay
				};
				uni.setStorageSync('sceneData', sceneData);
				this.sceneData = { ...sceneData };
				this.isMore = false;
			},
			// 添加条件触发器
			handleAddTrigger () {
				this.isTrigger = true;
			},
			// 添加执行动作
			handleAddAction () {
				this.isAction = true;
			},
			// 设备触发，租户
			goToDeviceList (type) {
				this.setSourceData(type, 1);
				uni.$u.route('/pagesA/scene/product/index', {
					type: type
				});
			},			// 设备触发，终端用户
			goToDeviceListTerminal (type) {
				this.setSourceData(type, 1);
				uni.$u.route('/pagesA/scene/product/device', {
					type: type
				});
			},
			// 产品触发
			goToProductList (type) {
				this.setSourceData(type, 3);
				uni.$u.route('/pagesA/scene/product/index', {
					type: type
				});
			},
			// 定时
			goToTimingList (type) {
				this.setSourceData(type, 2);
				uni.$u.route('/pagesA/scene/timing/index', {
					type: type
				});
			},
			// 告警列表
			goToWarningList (type) {
				this.setSourceData(type, 4);
				uni.$u.route('/pagesA/scene/warning/index');
			},
			// 获取设备图片
			getImageUrl (item) {
				if (item.source === 1) {
					return '/static/scene/device.png';
				} else if (item.source === 2) {
					return '/static/scene/timing.png';
				} else if (item.source === 3) {
					return '/static/scene/product.png';
				} else if (item.source === 4) {
					return '/static/scene/alarm.png';
				} else {
					return '';
				}
			},
			// 删除触发、执行项
			handleDeleteSceneItem (type, index) {
				const {
					triggers,
					actions
				} = this.sceneData;
				if (type === 'trigger') {
					const list = triggers.filter((item, i) => i !== index);
					this.sceneData = {
						...this.sceneData,
						triggers: [...list]
					};
				} else {
					const list = actions.filter((item, i) => i !== index);
					this.sceneData = {
						...this.sceneData,
						actions: [...list]
					};
				}
			},
			// 编辑触发、执行项, 小程序转换问题，所以用对象传进来
			handleEditSceneItem (val) {
				const storage = uni.getStorageSync(val.type);
				if (storage) {
					uni.removeStorageSync(val.type);
				}
				uni.setStorageSync(val.type, val.item);
				uni.removeStorageSync('callback');
				if (val.item.type === 5 || val.item.type === 6) {
					if (val.item.source === 1) {
						uni.$u.route('/pagesA/scene/product/device', {
							type: val.type,
							editIndex: val.index
						});
					} else if (val.item.source === 3) {
						uni.$u.route('/pagesA/scene/product/index', {
							type: val.type,
							editIndex: val.index
						});
					}
				} else {
					if (val.item.source === 1 || val.item.source === 3) {
						uni.$u.route('/pagesA/scene/product/model', {
							type: val.type,
							editIndex: val.index
						});
					} else if (val.item.source === 2) {
						uni.$u.route('/pagesA/scene/timing/index', {
							type: val.type,
							editIndex: val.index
						});
					} else if (val.item.source === 4) {
						uni.$u.route('/pagesA/scene/warning/index', {
							editIndex: val.index
						});
					}
				}
			},
			// 保存
			handleSave () {
				const {
					sceneId,
					sceneName,
					triggers,
					actions
				} = this.sceneData;
				if (!sceneName) {
					uni.showToast({
						icon: 'none',
						title: '场景名称不能为空',
					});
					return
				};
				if (triggers.length === 0) {
					uni.showToast({
						icon: 'none',
						title: '触发条件不能为空',
					});
					return
				};
				if (actions.length === 0) {
					uni.showToast({
						icon: 'none',
						title: '执行任务不能为空',
					});
					return
				};
				if (sceneId) {
					updateScene(this.sceneData).then(res => {
						if (res.code === 200) {
							uni.showToast({
								icon: 'none',
								title: '编辑成功',
							});
							uni.reLaunch({
								url: '/pages/tabBar/scene/index'
							});
						}
					});
				} else {
					addScene(this.sceneData).then(res => {
						if (res.code === 200) {
							uni.showToast({
								icon: 'none',
								title: '新增成功',
							});
							uni.reLaunch({
								url: '/pages/tabBar/scene/index'
							});
						}
					});
				}
			},
			getKey (index, item) {
				return `${index}-${item.id}`
			},
			// 存储条件、动作来源
			setSourceData (type, source) {
				let trigger = {
					id: '',
					name: '',
					operator: '',
					value: '',
					parentId: '', // 父类id
					parentName: '', // 父类名称
					arrayIndex: '', // 索引
					arrayIndexName: '', // 索引名称
					productId: null,
					productName: '',
					deviceCount: 0, // 设备数量
					deviceNums: [], // 设备编号
					isAdvance: 0, // 自定义cron
					cronExpression: '', // cron表达式
					source: 1, // 1=设备，2=定时，3=产品
					type: 1, // 1=属性，2=功能，3=事件
					scriptPurpose: 2, // 脚本用途（1=数据流，2=触发器，3=执行动作）
				};
				let action = {
					id: '',
					name: '',
					value: '',
					parentId: '',
					parentName: '',
					arrayIndex: '',
					arrayIndexName: '',
					productId: '',
					productName: '',
					deviceCount: 0,
					deviceNums: [],
					source: 1,
					type: 1,
					scriptPurpose: 3,
				};
				const storage = uni.getStorageSync(type);
				if (storage) {
					uni.removeStorageSync(type);
				}
				if (type === 'trigger') {
					trigger = {
						...trigger,
						source
					};
					uni.setStorageSync('trigger', trigger);
				} else {
					action = {
						...action,
						source
					};
					uni.setStorageSync('action', action);
				}
			}
		}
	};
</script>

<style>
	page {
		height: 100%;
		background: #eef3f7;
	}
</style>
<style lang="scss" scoped>
	.scene-detail-wrap {
		height: 100%;
		width: 100%;
		position: relative;

		.name-wrap {
			margin: 30rpx;
		}

		.container-wrap {
			padding-bottom: 140rpx;

			.cell-group-wrap {
				margin: 30rpx;

				.cell-wrap {
					background: #fff;
					border-radius: 12rpx;
				}
			}

			.condition-wrap,
			.execute-wrap {
				margin: 30rpx;
				background: #fff;
				border-radius: 12rpx;
				padding-bottom: 12rpx;

				.title-wrap {
					display: flex;
					flex-direction: row;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx;

					.left-wrap {
						flex: 1;
						display: flex;
						flex-direction: column;

						.title {
							font-size: 18px;
						}
					}

					.right-wrap {}
				}

				.empty-cell {
					padding: 30rpx;

					.text {
						height: 92rpx;
						border: 2rpx dashed #8686862e;
						border-radius: 12rpx;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
						font-size: 28rpx;
					}
				}

				.swipe-action-wrap {
					.action-item-wrap {

						&:not(:last-child) {
							border-bottom: 2rpx solid #eaeefb;
						}

						.slot-title {
							display: flex;
							flex-direction: row;
							align-items: center;

							.cell-text {
								display: flex;
								flex-direction: column;
								justify-content: center;
								margin-left: 24rpx;
								min-height: 124rpx;

								.title {
									font-size: 32rpx;
								}

								.des {
									font-size: 28rpx;
									color: #868686;
								}
							}
						}
					}
				}

				.btn-wrap {
					padding: 0 28rpx;
					margin-top: 30rpx;
				}
			}

			.btn-save-wrap {
				position: fixed;
				bottom: 0;
				left: 0;
				right: 0;
				z-index: 999;
				padding: 30rpx 26rpx 40rpx;
				background: #eef3f7f7;
			}
		}

		.other {
			.cond-popup-wrap {
				padding: 10rpx 0 20rpx;

				.cell-group-wrap {
					background: #eef3f7;

					.cell-wrap {
						text-align: center;
						background: #fff;

						&:last-child {
							margin-top: 15rpx;
						}
					}
				}
			}

			.more-popup-wrap {
				margin: 30rpx;

				.remark {
					color: #868686;
					font-size: 24rpx;
				}

				.form-wrap {
					margin: 30rpx 0;

					.form-item-wrap {
						background: #fff;
						border-radius: 12rpx;
						padding: 4rpx 30rpx;
						margin: 20rpx 0;
					}
				}
			}

			.trigger-popup-wrap {
				padding: 30rpx;

				.title {
					font-size: 32rpx;
					text-align: center;
					margin-bottom: 30rpx;
				}

				.cell-group-wrap {
					.cell-wrap {
						padding: 6rpx 0;
					}
				}
			}
		}
	}
</style>